package org.sherlock.plugins.revealers;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.sherlock.commons.model.RemoteFile;
import org.sherlock.commons.model.RemoteVideoFile;
import org.sherlock.commons.plugins.RevealerException;
import org.sherlock.commons.plugins.URLRevealer;

/**
 * 
 * @author Sherlock Downloader
 */
public class Revealer extends URLRevealer {

	// public Revealer() throws RevealerException, MalformedURLException {
	// String url =
	// "http://www.telecinco.es/piratas/VideoViewer/VideoViewer.shtml?videoURL=46831";
	// for (RemoteFile remoteFile : getURLs(new URL(url))) {
	// System.out.println(remoteFile.getRemoteAddress());
	// }
	// }
	@Override
	public ArrayList<RemoteFile> getURLs(URL url) throws RevealerException {
		ArrayList<RemoteFile> remoteFiles = new ArrayList<RemoteFile>();
		if (url.toString().contains("www.telecinco.es/") && url.toString().contains("VideoViewer.shtml?videoURL=")) {
			try {
				remoteFiles.add(getTele5Link(url.toString()));
			} catch (MalformedURLException ex) {
				Logger.getLogger(Revealer.class.getName()).log(Level.SEVERE, null, ex);
			} catch (IOException ex) {
				Logger.getLogger(Revealer.class.getName()).log(Level.SEVERE, null, ex);
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return remoteFiles;
	}

	private RemoteFile getTele5Link(String tele5Link) throws MalformedURLException, IOException, URISyntaxException {
		String token = tele5Link.split("=")[1];
		String link = "http://www.mitele.telecinco.es/services/tk.php?provider=level3&protohash=/CDN/videos/" + token.substring(token.length() - 3) + "/" + token + ".mp4";
		RemoteVideoFile remoteVideoFile = new RemoteVideoFile(new URI(getContent(new URL(link).openStream(), Charset.defaultCharset())));
		remoteVideoFile.setTitle(getContent(new URL("http://estaticos.telecinco.es/xml/Video/Video_" + token + ".xml").openStream(), Charset.defaultCharset()).split("\\[CDATA\\[")[1].split("\\]\\]")[0]);
		return remoteVideoFile;
	}
	// public static void main(String[] args) throws RevealerException,
	// MalformedURLException {
	// new Revealer();
	// }
}
